package com.aabte.server;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@Api(value = "/", description = "这是我全部的get方法")
public class MyGetMethod {

    @GetMapping("/get/cookies")
    @ApiOperation(value = "通过这个方法获取cookies")
    public String getCookies(@RequestParam String name,
                             @RequestParam String pass,
                             HttpServletRequest request,
                             HttpServletResponse response){
        if ("huhansan".equals(name) && "123456".equals(pass)){
            Cookie cookie = new Cookie("login", "true");
            response.addCookie(cookie);
            return "恭喜代获得Cookies信息成功！";
        } else {
            return "用户名密码错误！";
        }
    }
    
    @GetMapping("/get/with/cookies")
    @ApiOperation(value = "要求客户端携带cookies信息访问")
    public String getWithCookies(HttpServletRequest request,
                                 HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        if (!Objects.isNull(cookies)) {
            for (Cookie cookie :
                    cookies) {
                if ("login".equals(cookie.getName())
                        && "true".equals(cookie.getValue())) {
                    return "这是一个携带Cookies信息才能访问的Get请求";
                }
            }
        }
        return "必须携带Cookies信息！";
    }

    @GetMapping("/get/with/param")
    @ApiOperation(value = "需要携带查询参数访问")
    public Map<String, Integer> getList(@RequestParam Integer start,
                                        @RequestParam Integer end){
        return getMyList();
    }

    @GetMapping("/get/with/param/{start}/{end}")
    @ApiOperation(value = "需要携带Url参数访问")
    public Map<String, Integer> getList2(@PathVariable Integer start,
                                        @PathVariable Integer end){
        return getMyList();
    }

    private Map<String, Integer> getMyList(){
        Map<String, Integer> myList = new HashMap<>(3);
        myList.put("鞋", 400);
        myList.put("干脆面", 1);
        myList.put("衬衫", 300);
        return myList;
    }

}
